<template>
  <el-dialog
    v-zsdialogDrag
    :closeOnClickModal="false"
    title="判证结果"
    :visible.sync="dialogVisible"
    width="80%"
    top="10vh"
    @opened="initMapFn"
    :close-on-click-modal="false"
    class="bin_dialog no_padding dialog-1200"
  >
    <div class="map_dialog">
      <div class="map_left">
        <div id="map_box" ref="map"></div>
      </div>
      <div class="map_right">
        <div class="map_title">
          <div class="map_title_left">结果列表</div>
          <div class="map_title_right">
            <el-button class="bin_button" size="medium" icon="el-icon-upload">
              结果导出
            </el-button>
          </div>
        </div>
        <div class="map_list_wrap">
          <div class="map_list">
            <el-collapse class="ship_collapse">
              <el-collapse-item v-for="item in mapShipList" :key="item.id">
                <template slot="title">
                  <div class="map_items_title">
                    <div class="items_name">{{ item.shipInfo.name }}</div>
                    <div class="items_title_icons">
                      <div
                        class="title_icon_edit"
                        v-show="!item.isEditIng"
                        @click.stop="onEditShipItemFn(item)"
                      >
                        <el-tooltip
                          class="item"
                          effect="dark"
                          content="编辑"
                          placement="top"
                        >
                          <div class="el-icon-edit"></div>
                        </el-tooltip>
                      </div>
                      <div
                        class="title_icon_del"
                        @click.stop="onRemoveShipItemFn(item)"
                      >
                        <el-tooltip
                          class="item"
                          effect="dark"
                          content="删除"
                          placement="top"
                        >
                          <div class="el-icon-delete-solid"></div>
                        </el-tooltip>
                      </div>
                    </div>
                  </div>
                </template>
                <div class="map_items_content">
                  <div class="content_items">
                    <div class="items_name">船只名称</div>
                    <div class="items_val">
                      <el-input
                        v-model="item.editShipInfo.name"
                        class="ship_input"
                        :disabled="!item.isEditIng"
                        placeholder="请输入内容"
                      >
                      </el-input>
                    </div>
                  </div>
                  <div class="content_items">
                    <div class="items_name">船只经度</div>
                    <div class="items_val">
                      <el-input
                        v-model="item.editShipInfo.lon"
                        class="ship_input"
                        :disabled="!item.isEditIng"
                        placeholder="请输入内容"
                      >
                      </el-input>
                    </div>
                  </div>
                  <div class="content_items">
                    <div class="items_name">船只纬度</div>
                    <div class="items_val">
                      <el-input
                        v-model="item.editShipInfo.lat"
                        class="ship_input"
                        :disabled="!item.isEditIng"
                        placeholder="请输入内容"
                      >
                      </el-input>
                    </div>
                  </div>
                  <div class="content_items">
                    <div class="items_name">船只类型</div>
                    <div class="items_val">
                      <el-input
                        v-model="item.editShipInfo.type"
                        class="ship_input"
                        :disabled="!item.isEditIng"
                        placeholder="请输入内容"
                      >
                      </el-input>
                    </div>
                  </div>
                  <div class="content_items">
                    <div class="items_name">船只国别</div>
                    <div class="items_val">
                      <el-input
                        v-model="item.editShipInfo.country"
                        class="ship_input"
                        :disabled="!item.isEditIng"
                        placeholder="请输入内容"
                      >
                      </el-input>
                    </div>
                  </div>
                  <div class="content_items">
                    <div class="items_name">关联信号</div>
                    <div class="items_val">
                      <el-input
                        v-model="item.editShipInfo.signal"
                        class="ship_input"
                        :disabled="!item.isEditIng"
                        placeholder="请输入内容"
                      >
                      </el-input>
                    </div>
                  </div>
                  <div class="content_items">
                    <div class="items_name">开始时间</div>
                    <div class="items_val">{{ item.shipInfo.startTime }}</div>
                  </div>
                  <div class="content_items">
                    <div class="items_name">结束时间</div>
                    <div class="items_val">{{ item.shipInfo.endTime }}</div>
                  </div>
                  <div class="content_items_btns" v-show="item.isEditIng">
                    <el-button
                      class="bin_button"
                      size="mini"
                      @click="onShipEditCancelFn(item)"
                      >取消</el-button
                    >
                    <el-button
                      class="bin_button"
                      size="mini"
                      @click="onShipEditSubmitFn(item)"
                      >确认</el-button
                    >
                  </div>
                </div>
              </el-collapse-item>
            </el-collapse>
          </div>
        </div>
      </div>
    </div>
    <div id="ship_popup"></div>
  </el-dialog>
</template>

<script>
import "ol/ol.css";
import TileLayer from "ol/layer/Tile";
import VectorLayer from "ol/layer/Vector";
import VectorTile from "ol/source/VectorTile";
import VectorSource from "ol/source/Vector";
import Overlay from "ol/Overlay";
import OSM from "ol/source/OSM";
import XYZ from "ol/source/XYZ";
import MVT from "ol/format/MVT";
import TileWMS from "ol/source/TileWMS";
import { Map, View, Feature } from "ol";
import { Style, Stroke, Fill, Icon, Text, Circle } from "ol/style";
import { Polygon, MultiPolygon, Point, LineString } from "ol/geom";
import geomCircle from "ol/geom/Circle";
import { getVectorContext } from "ol/render";
import {
  ScaleLine,
  defaults as defaultControls,
  MousePosition,
} from "ol/control";
import { format } from "ol/coordinate";
import { transform, toLonLat } from "ol/proj";
import { defaults } from "ol/interaction";
import shipPng from "../../../../assets/jianchuan-blue.png";
export default {
  data() {
    return {
      dialogVisible: true,
      mapShipList: [
        {
          id: "1",
          isEditIng: false,
          shipInfo: {
            name: "船只1",
            type: "类型1",
            country: "中国",
            signal: "CW、LFM",
            startTime: "2041-51-51 15:15:12",
            endTime: "2041-51-51 15:15:12",
            lon: "120",
            lat: "30",
          },
          editShipInfo: {
            name: "船只1",
            type: "类型1",
            country: "中国",
            signal: "CW、LFM",
            startTime: "2041-51-51 15:15:12",
            endTime: "2041-51-51 15:15:12",
            lon: "120",
            lat: "30",
          },
        },
        {
          id: "2",
          isEditIng: false,
          shipInfo: {
            name: "船只22",
            type: "类型22",
            country: "中国",
            signal: "CW、LFM",
            startTime: "2041-51-51 15:15:12",
            endTime: "2041-51-51 15:15:12",
            lon: "111",
            lat: "28",
          },
          editShipInfo: {
            name: "船只22",
            type: "类型22",
            country: "中国",
            signal: "CW、LFM",
            startTime: "2041-51-51 15:15:12",
            endTime: "2041-51-51 15:15:12",
            lon: "111",
            lat: "28",
          },
        },
      ],
      centerCoodinate: [110, 32],
      mapInstance: null,
      popupObj: null,
      shipLayer: null,
    };
  },
  methods: {
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~功能项的 ~~~~~~~~~~~~~~~~~~~~~~~~~~
    // 修改船只信息
    onEditShipItemFn(item) {
      if (item.isEditIng) {
        return;
      }
      let flag = this.mapShipList.some((item22) => {
        return item22.isEditIng;
      });
      if (flag) {
        this.$message({
          message: "请先完成其他船只的修改~",
          type: "warning",
        });
      } else {
        this.mapShipList = this.mapShipList.map((item22) => {
          return { ...item22, isEditIng: item22.id === item.id };
        });
      }
    },
    // 删除船只信息
    onRemoveShipItemFn(item) {
      this.$confirm("此操作将删除该船只, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.mapShipList = this.mapShipList.filter((ele) => {
          return ele.id !== item.id;
        });
        this.onDelMapShipInfoFn(item);
        this.$message({
          type: "success",
          message: "删除成功!",
        });
      });
    },
    // 修改船只下的确认按钮
    onShipEditSubmitFn(item) {
      let newItem = {
        ...item,
        shipInfo: JSON.parse(JSON.stringify(item.editShipInfo)),
        isEditIng: false,
      };
      this.mapShipList = this.mapShipList.map((item22) => {
        if (item22.id === item.id) {
          return newItem;
        } else {
          return item22;
        }
      });
      this.onUpdateMapShipInfoFn(newItem);
    },
    // 修改船只下的取消按钮
    onShipEditCancelFn(item) {
      let newItem = {
        ...item,
        editShipInfo: JSON.parse(JSON.stringify(item.shipInfo)),
        isEditIng: false,
      };
      console.log(newItem);
      this.mapShipList = this.mapShipList.map((item22) => {
        if (item22.id === item.id) {
          return newItem;
        } else {
          return item22;
        }
      });
    },
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~地图项的 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    //   初始化地图
    initMapFn() {
      this.$nextTick(() => {
        if (!this.mapInstance) {
          this.mapInstance = new Map({
            //加载控件到地图容器中
            controls: defaultControls({
              zoom: false, //不显示放大缩小按钮
              rotate: false, //不显示指北针控件
            }).extend([new ScaleLine()]), //比例尺
            target: this.$refs.map, //目标容器
            layers: [
              new TileLayer({
                source: this.sourceMaoHeaderFn(),
              }),
            ],
            loadTilesWhileAnimating: true, //加载时的动画过度
            interactions: new defaults({
              doubleClickZoom: false,
            }),
            view: new View({
              //视口地图相关配置
              projection: "EPSG:3857", //3857为墨卡托坐标，4326为gps经纬度
              center: this.gisPosTransform1(this.centerCoodinate), //设置默认的视角中心点
              zoom: 4, //缩放级别
              minZoom: 2,
              maxZoom: 8,
            }),
          });
          this.forEachShipPointToMapFn();
          this.addPopUpInMapFn();
          this.setMapClickFn();
        }
      });
    },
    // 给source 添加请求头
    sourceMaoHeaderFn() {
      let source = new XYZ({
        url:
          process.env.VUE_APP_BASE_API +
          "/underwater-sound/maps/{z}/{x}/{y}.png",
      });
      source.setTileLoadFunction((tile, src) => {
        const xhr = new XMLHttpRequest();
        xhr.responseType = "blob";
        xhr.addEventListener("loadend", function (evt) {
          const data = this.response;
          if (data !== undefined) {
            tile.getImage().src = URL.createObjectURL(data);
          } else {
            tile.setState(TileState.ERROR);
          }
        });
        xhr.addEventListener("error", function () {
          tile.setState(TileState.ERROR);
        });
        xhr.open("GET", src);
        xhr.setRequestHeader(
          "Authorization",
          `Bearer ${this.$store.state.token}`
        );
        xhr.send();
      });
      return source;
    },
    // 经纬度转墨卡托坐标
    gisPosTransform1(pos) {
      return transform(pos, "EPSG:4326", "EPSG:3857");
    },
    // 墨卡托转经纬度坐标
    gisPosTransform2(pos) {
      return transform(pos, "EPSG:3857", "EPSG:4326");
    },
    // 更新地图上的船只信息
    onUpdateMapShipInfoFn(item) {
      let source = this.shipLayer.getSource();
      let featureItem = null;
      source.forEachFeature((feature) => {
        if (feature.SHIPID === item.id) {
          featureItem = feature;
          return false;
        }
      });
      let newLonLatArr = this.gisPosTransform1([
        item.shipInfo.lon,
        item.shipInfo.lat,
      ]);
      featureItem.OPTIONSParams = item;
      featureItem.getGeometry().setCoordinates(newLonLatArr);
      this.isHideMapPopupFn();
      this.mapInstance.render();
    },
    // 删除地图上的船只信息
    onDelMapShipInfoFn(item) {
      let source = this.shipLayer.getSource();
      let featureItem = null;
      source.forEachFeature((feature) => {
        if (feature.SHIPID === item.id) {
          featureItem = feature;
          return false;
        }
      });
      this.isHideMapPopupFn();
      source.removeFeature(featureItem);
    },
    // 循环生成坐标点
    forEachShipPointToMapFn() {
      let featuresArr = this.mapShipList.map((item) => {
        return this.onDrawPointFn(item);
      });
      this.shipLayer = new VectorLayer({
        source: new VectorSource({
          features: featuresArr,
        }),
        style: null,
        name: "shipLayer ",
        visible: true,
      });
      this.mapInstance.addLayer(this.shipLayer);
    },
    // 绘制point
    onDrawPointFn(item) {
      let { shipInfo, id } = item;
      let tranPos = this.gisPosTransform1([shipInfo.lon, shipInfo.lat]);
      let point = new Point(tranPos);
      let feature = new Feature(point);
      feature.setStyle(this.pointColor());
      feature.SHIPID = id;
      feature.OPTIONSParams = item;
      return feature;
    },
    // point的样式
    pointColor() {
      return new Style({
        image: new Icon({
          anchor: [0.5, 46],
          scale: 0.7,
          anchorXUnits: "fraction",
          anchorYUnits: "pixels",
          src: shipPng,
        }),
      });
    },
    // 增加弹出窗
    addPopUpInMapFn() {
      this.popupObj = new Overlay({
        element: document.getElementById("ship_popup"),
        positioning: "center-right",
        stopEvent: false,
        offset: [-40, -12],
      });
      this.mapInstance.addOverlay(this.popupObj);
    },
    // 自定义事件的htmlBox
    diyThingHtmlBoxFn(item) {
      let { shipInfo } = item;
      // 头部标题
      let titleBox = `<div class='ship_title'>船只信息</div>`;
      // 内容中的小盒子
      let smBox3 = `<div class='ship_item'><div class='ship_item_name'>船只名称</div><div class='ship_item_val'>${shipInfo.name}</div></div>`;
      let smBox1 = `<div class='ship_item'><div class='ship_item_name'>经度</div><div class='ship_item_val'>${shipInfo.lon}</div></div>`;
      let smBox2 = `<div class='ship_item'><div class='ship_item_name'>纬度</div><div class='ship_item_val'>${shipInfo.lat}</div></div>`;
      let smBox4 = `<div class='ship_item'><div class='ship_item_name'>船只类别</div><div class='ship_item_val'>${shipInfo.type}</div></div>`;
      let smBox5 = `<div class='ship_item'><div class='ship_item_name'>船只国别</div><div class='ship_item_val'>${shipInfo.country}</div></div>`;
      let smBox6 = `<div class='ship_item'><div class='ship_item_name'>关联信号</div><div class='ship_item_val'>${shipInfo.signal}</div></div>`;
      let smBox7 = `<div class='ship_item'><div class='ship_item_name'>开始时间</div><div class='ship_item_val'>${shipInfo.startTime}</div></div>`;
      let smBox8 = `<div class='ship_item'><div class='ship_item_name'>结束时间</div><div class='ship_item_val'>${shipInfo.endTime}</div></div>`;
      let contentBox = `<div class='ship_list'>${smBox3}${smBox1}${smBox2}${smBox4}${smBox5}${smBox6}${smBox7}${smBox8}</div>`;
      let triBox = `<div class='ship_tri'></div>`;
      let mainBox = `${titleBox}${contentBox}${triBox}`;
      return mainBox;
    },
    // 地图的点击事件
    setMapClickFn() {
      this.mapInstance.on("click", (evt) => {
        const feature = this.mapInstance.forEachFeatureAtPixel(
          evt.pixel,
          function (feature) {
            return feature;
          }
        );
        console.log(feature, evt);
        if (feature) {
          // 设置弹窗位置并显示
          this.popupObj.setPosition(feature.getGeometry().getCoordinates());
          const element = this.popupObj.getElement();
          if (element) {
            element.innerHTML = this.diyThingHtmlBoxFn(feature.OPTIONSParams);
          }
        } else {
          this.popupObj.setPosition(undefined);
        }
      });
    },
    // 消除地图上的popup展示
    isHideMapPopupFn() {
      this.popupObj.setPosition(undefined);
    },
  },
};
</script>

<style lang="scss" scoped>
.map_dialog {
  display: flex;
  width: 100%;
  height: 840px;

  .map_left {
    flex: 1 1 auto;
    width: 0;
    height: 100%;

    #map_box {
      width: 100%;
      height: 100%;
    }
  }

  .map_right {
    flex: 0 0 auto;
    width: 450px;
    height: 100%;
    border-left: 1px solid #02fff4;
    display: flex;
    flex-direction: column;

    .map_title {
      display: flex;
      align-items: center;
      justify-content: space-between;
      flex: 0 0 auto;
      width: 100%;
      height: 54px;
      line-height: 54px;
      box-sizing: border-box;
      padding: 0 32px;
      border-bottom: 1px solid #02fff4;
      color: #fff;
      font-size: 20px;
      background-color: rgba(2, 255, 244, 0.2);
      position: relative;

      &::after {
        content: "";
        background-color: #02fff4;
        position: absolute;
        width: 5px;
        height: 20px;
        left: 16px;
        top: 50%;
        transform: translateY(-50%);
      }
    }

    .map_list_wrap {
      flex: 1 1 auto;
      width: 100%;
      height: 0;
      box-sizing: border-box;
      padding: 0 4px;
      overflow: hidden;
      margin: 16px 0;

      ::v-deep .map_list {
        width: 100%;
        height: 100%;
        box-sizing: border-box;
        padding: 0 16px;
        overflow: auto;

        .ship_collapse {
          border-color: transparent;

          .el-collapse-item {
            .el-collapse-item__header {
              color: #fff;
              background: rgba(0, 94, 123, 0.7);
              box-shadow: inset 0px 0px 12px 1px #02fff4;
              border: 1px solid #02fff4;
              box-sizing: border-box;
              padding: 0 20px;
              font-size: 20px;

              .map_items_title {
                width: 90%;
                display: flex;
                align-items: center;
                justify-content: space-between;

                .items_title_icons {
                  display: flex;
                  align-items: center;

                  .title_icon_edit,
                  .title_icon_del {
                    font-size: 24px;
                    color: #fff;
                    margin: 0 5px;
                  }
                }
              }
            }

            .el-collapse-item__wrap {
              border-color: transparent;
              background-color: transparent;

              .el-collapse-item__content {
                background-color: transparent;

                .map_items_content {
                  .content_items {
                    display: flex;
                    align-items: center;
                    width: 100%;
                    height: 50px;
                    box-sizing: border-box;
                    border: 1px solid #02fff4;
                    font-size: 20px;
                    color: #fff;

                    .items_name {
                      flex: 0 0 auto;
                      width: 150px;
                      height: 100%;
                      border-right: 1px solid #02fff4;
                      line-height: 48px;
                      text-align: center;
                      background: rgba(1, 75, 97, 0.8);
                      padding: 0 12px;
                      box-sizing: border-box;
                      text-overflow: ellipsis;
                      overflow: hidden;
                      white-space: nowrap;
                    }

                    .items_val {
                      flex: 1 1 auto;
                      width: 0;
                      line-height: 48px;
                      padding: 0 12px;
                      background-color: rgba(2, 26, 39, 0.5);
                      box-sizing: border-box;
                      text-overflow: ellipsis;
                      overflow: hidden;
                      white-space: nowrap;

                      .ship_input {
                        &.is-disabled {
                          .el-input__inner {
                            background: transparent;
                            border-color: transparent;
                            color: #fff;
                            cursor: default;
                          }
                        }

                        .el-input__inner,
                        .el-textarea__inner {
                          background-color: transparent;
                          border-color: transparent;
                          color: #fff;
                          font-size: 20px;
                          padding: 0;
                        }
                      }
                    }
                  }

                  .content_items_btns {
                    display: flex;
                    align-items: center;
                    width: 100%;
                    height: 50px;
                    box-sizing: border-box;
                    border: 1px solid #02fff4;
                    font-size: 20px;
                    color: #fff;
                    justify-content: center;
                  }
                }
              }
            }
          }
        }
      }
    }
  }

  ::v-deep #ship_popup {
    width: 380px;
    background: rgba(7, 47, 70, 0.9);
    border: 1px solid #02fff4;
    box-sizing: border-box;
    position: relative;

    .ship_title {
      width: 100%;
      height: 54px;
      box-sizing: border-box;
      padding: 0 18px;
      line-height: 54px;
      background: rgba(2, 255, 244, 0.2);
      font-size: 20px;
      color: #fff;
    }

    .ship_list {
      box-sizing: border-box;
      padding: 20px;

      .ship_item {
        font-size: 18px;
        color: #02fff4;
        display: flex;
        align-items: center;
        margin-top: 8px;

        &:first-child {
          margin-top: 0;
        }

        .ship_item_name {
          flex: 0 0 auto;
          width: 90px;
        }

        .ship_item_val {
          flex: 1 1 auto;
          width: 100%;
          height: 44px;
          line-height: 42px;
          background: rgba(2, 69, 93, 0.6);
          border: 1px solid rgba(2, 255, 244, 0.6);
          box-sizing: border-box;
          padding: 0 18px;
        }
      }
    }

    .ship_tri {
      position: absolute;
      top: 50%;
      right: -28px;
      transform: translateY(-50%);
      border: 15px solid transparent;
      border-left-color: rgba(7, 47, 70, 0.9);
    }
  }
}
</style>
